package net.bolue.sysmng.db;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.bolue.sysmng.exception.BolueException;
import net.bolue.sysmng.tblbean.DbRes;
import net.bolue.sysmng.util.PropertiesLoader;
import net.bolue.sysmng.util.SysCostants;
import net.bolue.web.report.RepConstants;

/**
 * 数据库连接类
 * @author Administrator
 *
 */
public class DbConnector {

	/**
	 * 通过数据库资源标志连接
	 * @param dbResId	资源标志,配置文件连接标志system
	 * @return
	 */
	public static Connection getConnection(String dbResId) throws BolueException{
		Connection conn = DBPool.getInstance().getConnection(dbResId);
		if(conn!=null){
			return conn;
		}
		if(RepConstants.SYSMNG_SUBSYS_KEY.equals(dbResId)){
			return getConnectionByConf();
		}
		DbRes dbRes = getDbRes(dbResId);
		
		if(dbRes==null){
			return null;
		}
		
		if(dbRes.getConnType()==1){
			return getConnectionByDb(dbRes);
		} else if(dbRes.getConnType()==2){
			return getConnectionByConf(dbRes);
		}
		return null;
	}
	
	/**
	 * 通过数据源连接
	 * @param dbRes
	 * @return
	 */
	private static Connection getConnectionByDb(DbRes dbRes)throws BolueException{
		Connection conn = DBPool.getInstance().getConnection(dbRes);
		return conn;
	}
	
	/**
	 * 通过配置文件连接
	 * @param dbRes
	 * @return
	 */
	private static Connection getConnectionByConf(DbRes dbRes)throws BolueException{
		Connection conn = DBPool.getInstance().getConnection(dbRes);
		return conn;
	}
	
	/**
	 * 通过配置文件连接
	 * @return
	 */
	private static Connection getConnectionByConf()throws BolueException{
		String dbUrl = PropertiesLoader.getKeyValue(SysCostants.DB_PROPERTIES, "ConnectString");
		String dbUser = PropertiesLoader.getKeyValue(SysCostants.DB_PROPERTIES, "UserID");
		String passwd = PropertiesLoader.getKeyValue(SysCostants.DB_PROPERTIES, "Password");
		String dbDriver = PropertiesLoader.getKeyValue(SysCostants.DB_PROPERTIES, "JdbcDriverName");
		
		DbRes dbRes = new DbRes();
		dbRes.setDbResId(RepConstants.SYSMNG_SUBSYS_KEY);
		dbRes.setConnType(2);
		dbRes.setDbDriver(dbDriver);
		dbRes.setDbType(1);
		dbRes.setDbUrl(dbUrl);
		dbRes.setDbUser(dbUser);
		dbRes.setPasswd(passwd);
		Connection conn = DBPool.getInstance().getConnection(dbRes);
		return conn;
	}
	
	private static DbRes getDbRes(String dbResId)throws BolueException{
		Map<String,Object> whereMap = new HashMap<String,Object>();
		whereMap.put("DBRESID", dbResId);
		DbOpUtil dbOpUtil = new DbOpUtil(RepConstants.SYSMNG_SUBSYS_KEY);
		return dbOpUtil.getOne(DbRes.class, "st_dbres", null, whereMap);
	}
}
